package com.ktgj.service.service.impl;

import java.math.BigDecimal;
import java.rmi.server.ExportException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.common.core.utils.SnowflakeUtils;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.Customer;
import com.ktgj.customer.api.domain.CustomerCard;
import com.ktgj.service.domain.OrderOperationlog;
import com.ktgj.service.domain.OrderitemBoarding;
import com.ktgj.service.domain.vo.*;
import com.ktgj.service.mapper.OrderOperationlogMapper;
import com.ktgj.service.mapper.OrderitemBoardingMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.service.mapper.OrderBoardingMapper;
import com.ktgj.service.domain.OrderBoarding;
import com.ktgj.service.service.IOrderBoardingService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 值机订单
Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-09-03
 */
@Transactional
@Service
public class OrderBoardingServiceImpl implements IOrderBoardingService 
{
    @Autowired
    private OrderBoardingMapper orderBoardingMapper;

    @Autowired
    private OrderitemBoardingMapper orderitemBoardingMapper;

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    @Autowired
    private OrderOperationlogMapper orderOperationlogMapper;

    /**
     * 查询值机订单

     * 
     * @param orderboardingId 值机订单
ID
     * @return 值机订单

     */
    @Override
    public OrderBoarding selectOrderBoardingById(Long orderboardingId)
    {
        return orderBoardingMapper.selectOrderBoardingById(orderboardingId);
    }

    /**
     * 查询值机订单
列表
     * 
     * @param orderBoarding 值机订单

     * @return 值机订单

     */
    @Override
    public List<OrderBoarding> selectOrderBoardingList(OrderBoarding orderBoarding)
    {
        return orderBoardingMapper.selectOrderBoardingList(orderBoarding);
    }

    /**
     * 值机订单  查看详情
     * @param orderboardingId 值机订单ID
     * @return 值机订单
     * */
    @Override
    public OrderBoarding selectOrderBoardingByOrderboardingId(Long orderboardingId) {
        return orderBoardingMapper.selectOrderBoardingByOrderboardingId(orderboardingId);
    }

    /**
     * 新增值机订单

     * 
     * @param orderBoarding 值机订单

     * @return 结果
     */
    @Override
    public int insertOrderBoarding(OrderBoarding orderBoarding)
    {
        orderBoarding.setCreateTime(DateUtils.getNowDate());
        return orderBoardingMapper.insertOrderBoarding(orderBoarding);
    }

    /**
     * 修改值机订单

     * 
     * @param orderBoarding 值机订单

     * @return 结果
     */
    @Override
    public int updateOrderBoarding(OrderBoarding orderBoarding)
    {
        orderBoarding.setUpdateTime(DateUtils.getNowDate());
        return orderBoardingMapper.updateOrderBoarding(orderBoarding);
    }

    /**
     * 批量删除值机订单

     * 
     * @param orderboardingIds 需要删除的值机订单
ID
     * @return 结果
     */
    @Override
    public int deleteOrderBoardingByIds(Long[] orderboardingIds)
    {
        return orderBoardingMapper.deleteOrderBoardingByIds(orderboardingIds);
    }

    /**
     * 删除值机订单
信息
     * 
     * @param orderboardingId 值机订单
ID
     * @return 结果
     */
    @Override
    public int deleteOrderBoardingById(Long orderboardingId)
    {
        return orderBoardingMapper.deleteOrderBoardingById(orderboardingId);
    }

    /**
     * 值机订单与值机订单详细新增
     * @param orderBoarding  值机对象
     * @return 结果
     * */
    @Override
    public int insertOrderBoardingAndOrderitemBoarding(OrderBoarding orderBoarding) {
        /**
         * 记录值机订单明细结果
         * 新增成功，则itemCount!=0;
         * 新增失败，则itemCount==0;
         *  */
        int itemCount=0;

        SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
        /** 生成值机订单表金色世纪ID */
        orderBoarding.setJsjId(Long.valueOf(snowflakeUtils.nextId()));

        /** 值机订单表 使用进厅次数 = 乘机人集合长度*/
        orderBoarding.setUsedcheckinNum((long) orderBoarding.getOrderitemBoardings().size());
        int boardingCount=orderBoardingMapper.insertOrderBoarding(orderBoarding);

        /**
         * 事务回滚判断
         * boardingCount>0;   继续执行
         * boardingCount<=0;   回滚事务
         * */
        if (boardingCount>0){

            /** 遍历值机订单明细集合 */
            for (OrderitemBoarding orderitemBoarding:orderBoarding.getOrderitemBoardings()){
                orderitemBoarding.setCreateTime(DateUtils.getNowDate());
                orderitemBoarding.setOrderboardingId(orderBoarding.getJsjId());

                itemCount=orderitemBoardingMapper.insertOrderitemBoarding(orderitemBoarding);
            }
        }
        return itemCount;
    }

    /**
     * 查询会员值机订单
     * */
    @Override
    public List<OrderBoarding> selectOrderBoardingByCustomer(Customer customer, Long type) {
        List<OrderBoarding> orderBoardingList = orderBoardingMapper.selectOrderBoardingByCustomer(customer.getCustomerName(), customer.getContractPhoneOne(), type);
        return orderBoardingList;
    }

    /**
     * 查询登机牌票量数据
     * */
    @Override
    public BoardingPassVo selectOrderBoardingNum(Long customerId) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy");
//        List<CustomerCard> customerCards = remoteCustomerService.queryCardIdByCustomerId(customerId);//会员 卡号
//
//        for (com.ktgj.customer.api.domain.CustomerCard customerCard : customerCards) {
//            if (customerCard.getCardId() != null && customerCard.getCardId() != 0){
//                Map<String, Object> map = new HashMap<>();
//                map.put("cardId", customerCard.getCardId());
//                Card card = remoteCustomerService.cardInfo(map);
//                if (card != null){
//                    customerCard.setCardLevel(card.getCardLevel());
//                }
//                else {
//                    throw new Exception("无效的会员卡");
//                }
//            }
//            else {
//                throw new Exception("会员卡没有关联卡id");
//            }
//        }
//
//        customerCards.sort((y, x) -> Double.compare(y.getCardLevel(), x.getCardLevel()));
//        com.ktgj.customer.api.domain.CustomerCard customerCardR = customerCards.get(0);
//
//        String cardNumber = customerCardR.getCardCode();

        List<OrderBoarding> orderBoardingList = orderBoardingMapper.selectOrderBoardingNum(customerId);
        if (orderBoardingList != null && orderBoardingList.size() > 0){
            BoardingPassVo boardingPassVo = new BoardingPassVo();
            boardingPassVo.setUsageCountNum(orderBoardingList.size());

            List<SummaryOfVotesVo> summaryOfVotesVoList = new ArrayList<>();
            List<String> timeList = GetYears();

            for (String time : timeList) {
                List<OrderBoarding> orderBoardings = new ArrayList<>();
                SummaryOfVotesVo summaryOfVotesVo = new SummaryOfVotesVo();
                summaryOfVotesVo.setYears(time);
                for (OrderBoarding orderBoarding : orderBoardingList) {
                    if (format.format(orderBoarding.getCreateTime()).compareTo(time) == 0){
                        orderBoardings.add(orderBoarding);
                    }
                }
                summaryOfVotesVo.setTicketAmount(orderBoardings.size());
                summaryOfVotesVoList.add(summaryOfVotesVo);
            }
            boardingPassVo.setSummaryOfVotesVoList(summaryOfVotesVoList);
            return boardingPassVo;
        }
        else {
            throw new Exception("没有数据");
        }
    }

    /**
     * 值机选座
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addOrderBoarding(OrderBoardingVo orderBoardingVo) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Long orderId = System.currentTimeMillis() / 1000;
        OrderBoarding orderBoarding = new OrderBoarding();
        orderBoarding.setOrderboardingId(orderId);
        orderBoarding.setFlightNumber(orderBoardingVo.getFlightNumber());
        orderBoarding.setContactName(orderBoardingVo.getCustomerName());
        orderBoarding.setSourceappId(orderBoardingVo.getType());
        orderBoarding.setDepartureCity(orderBoardingVo.getDepartureCity());
        orderBoarding.setArrivalCity(orderBoardingVo.getArrivalCity());
        orderBoarding.setAirlineCode(orderBoardingVo.getAirlineCode());
        try {
            orderBoarding.setDepartureTime(format.parse(orderBoardingVo.getFlightDate()));
        } catch (Exception e){
            throw new Exception("日期转换错误");
        }
        orderBoarding.setContactPhone(orderBoardingVo.getContactPhone());

        if (orderBoardingVo.getSeatingArea() != null && !orderBoardingVo.getSeatingArea().equals("")){
            orderBoarding.setTravellerseatNear(orderBoardingVo.getSeatingArea());
            orderBoarding.setHasSelectedsets("true");
        }
        else {
            orderBoarding.setTravellerseatNear(EmHelper.SeatingArea.random.getValue());
            orderBoarding.setHasSelectedsets("false");
        }

        orderBoarding.setStatus(EmHelper.SeatingArea.undone.getValue());
        orderBoarding.setIsDeleted("false");
        orderBoarding.setTotalSaleprice(new BigDecimal(0));
        orderBoarding.setCreateTime(format.parse(format.format(new Date())));
        orderBoarding.setItinerary(orderBoardingVo.getItinerary());

        Long orderNum = System.currentTimeMillis() / 1000;
        orderBoarding.setOrderboardingId(orderNum);
        if (orderBoardingVo.getType().equals("Crm")){
            orderBoarding.setStatus(EmHelper.OrderStatus.Offline.getValue());
        }
        else {
            orderBoarding.setStatus(EmHelper.OrderStatus.Online.getValue());
        }
        orderBoarding.setCustomerId(orderBoardingVo.getCustomerId());
        int i = orderBoardingMapper.insertOrderBoarding(orderBoarding);
        if (i > 0){
            if (orderBoardingVo.getCommonTravelersIds() != null && orderBoardingVo.getCommonTravelersIds().size() > 0){
                for (PassengerVo commonTravelersId : orderBoardingVo.getCommonTravelersIds()) {
                    OrderitemBoarding orderitemBoarding = new OrderitemBoarding();
                    orderitemBoarding.setOrderboardingId(orderId);
                    orderitemBoarding.setGuestName(commonTravelersId.getGuestName());
                    orderitemBoarding.setIdTypeid(commonTravelersId.getIdTypeId());
                    orderitemBoarding.setIdNumber(commonTravelersId.getIdNumber());
                    orderitemBoarding.setSalePrice(new BigDecimal(0));
                    orderitemBoarding.setStatus(EmHelper.SeatingArea.undone.getValue());
                    Date date = format.parse(format.format(new Date()));
                    orderitemBoarding.setCrateTime(date);
                    int boarding = orderitemBoardingMapper.insertOrderitemBoarding(orderitemBoarding);
                    //会员消息
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    String orderDate = sdf.format(orderBoarding.getCreateTime());
                    String star = "您在" + orderDate +"预定" +orderitemBoarding.getSeatNubmer()+"号作为"+"值机选座成功"+"请在规定时间内登机";

                    Map<String, String> map = new HashMap<>();
                    map.put("messageContent", star);
                    map.put("businessType", EmHelper.businessType.CheckIn.getValue());
                    map.put("customerId",orderBoardingVo.getCustomerId().toString());
                    map.put("businessOrderId",orderNum.toString());
                    remoteCustomerService.addCustomerMessage(map);
                    if (boarding <= 0){
                        throw new Exception("子订单" + commonTravelersId.getGuestName() + "创建失败");
                    }
                }
            }
            else {
                throw new Exception("乘机人信息不能为空");
            }
        }
        else {
            throw new Exception("订单创建失败");
        }
        return i;
    }

    /**
     * 登机牌订单列表
     * */
    @Override
    public List<OrderBoarding> selectVipchannelOrederList(VipchannelOrederParameterVo vipchannelOrederParameterVo) {
        List<OrderBoarding> orderBoardingList = orderBoardingMapper.selectVipchannelOrederList(vipchannelOrederParameterVo);
            return orderBoardingList;
    }

    /**
     * 登机牌订单详细
     * */
    @Override
    public OrderViphallDetailsVo selectBoarding(Long orderId, String orderNum) throws Exception {
        if ((orderId != null && orderId != 0) || (orderNum != null && !orderNum.equals(""))){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

            OrderBoarding orderBoarding;
            if (orderId != null){
                orderBoarding = orderBoardingMapper.selectOrderBoardingDetailed(orderId);
            }
            else{
                orderBoarding = orderBoardingMapper.orderBoardingDetailed(orderNum);
            }

            if (orderBoarding != null){
                OrderViphallDetailsVo orderViphallDetailsVo = new OrderViphallDetailsVo();
                orderViphallDetailsVo.setOrderId(orderBoarding.getOrderboardingId());
                if (orderBoarding.getCustomerId() != null && orderBoarding.getCustomerId() != 0){
                    Customer customer = remoteCustomerService.getCustomerId(orderBoarding.getCustomerId()).getData();
                    orderViphallDetailsVo.setCustomerName(customer.getCustomerName());
                    orderViphallDetailsVo.setCustomerPhone(customer.getContractPhoneOne());
                }
                orderViphallDetailsVo.setCustomerCard(orderBoarding.getCardNumber());
                if (orderBoarding.getCreateTime() != null){
                    orderViphallDetailsVo.setCreateTime(format.format(orderBoarding.getCreateTime()));
                }
                orderViphallDetailsVo.setSourceAppId(orderBoarding.getSourceappId() + " " + orderBoarding.getSourceCompanyid());
                orderViphallDetailsVo.setContactName(orderBoarding.getContactName());
                orderViphallDetailsVo.setContactPhone(orderBoarding.getContactPhone());
                orderViphallDetailsVo.setOrderNum(orderBoarding.getOrderNum());
                orderViphallDetailsVo.setOrderStatus(orderBoarding.getStatus());
                orderViphallDetailsVo.setServiceItems(orderBoarding.getServiceItems());
                orderViphallDetailsVo.setBoardingType(orderBoarding.getCheckinserviceId());
                orderViphallDetailsVo.setReserveNum(orderBoarding.getUsedcheckinNum());
                if (orderBoarding.getTravellerseatNear() != null && !orderBoarding.getTravellerseatNear().equals("")){
                    orderViphallDetailsVo.setSeatingArea(orderBoarding.getTravellerseatNear());
                }
                orderViphallDetailsVo.setCityName(orderBoarding.getDepartureCity());
                orderViphallDetailsVo.setSetOffAirport(orderBoarding.getAirport());
                orderViphallDetailsVo.setDepartuprairportTerminalName(orderBoarding.getDepartureAirportterminalname());
                orderViphallDetailsVo.setFlightNumber(orderBoarding.getFlightNumber());
                orderViphallDetailsVo.setDeparturesCity(orderBoarding.getDepartureCity());
                orderViphallDetailsVo.setArrivalCity(orderBoarding.getArrivalCity());
                if (orderBoarding.getDepartureTime() != null){
                    orderViphallDetailsVo.setDepartureTime(format.format(orderBoarding.getDepartureTime()));
                }

                if (orderBoarding.getArrivalTime() != null){
                    orderViphallDetailsVo.setArrivalTime(format.format(orderBoarding.getArrivalTime()));
                }

                orderViphallDetailsVo.setRemark(orderBoarding.getRemark());

                List<OrderItemViphallVo> orderItemViphallVoList = new ArrayList<>();
                List<OrderitemBoarding> orderitemBoardingList = orderitemBoardingMapper.orderitemBoardingList(orderBoarding.getOrderboardingId());
                if (orderitemBoardingList != null && orderitemBoardingList.size() > 0){
                    for (OrderitemBoarding orderitemBoarding : orderitemBoardingList) {
                        OrderItemViphallVo orderItemViphallVo = new OrderItemViphallVo();
                        orderItemViphallVo.setOrderItemBoardingId(orderitemBoarding.getOrderitemboardingId());
                        orderItemViphallVo.setGuestName(orderitemBoarding.getGuestName());
                        orderItemViphallVo.setIdNumber(orderitemBoarding.getIdNumber());
                        orderItemViphallVo.setSeatNumber(orderitemBoarding.getSeatNubmer());
                        orderItemViphallVo.setStatus(orderitemBoarding.getStatus());
                        orderItemViphallVo.setPDF417(orderitemBoarding.getPdf417());
                        orderItemViphallVo.setCODE128(orderitemBoarding.getCode128());
                        orderItemViphallVo.setBoardingPassImagepath(orderitemBoarding.getBoardingpassImagepath());
                        orderItemViphallVoList.add(orderItemViphallVo);
                    }
                    orderViphallDetailsVo.setOrderItemViphallVoList(orderItemViphallVoList);
                }
                if (orderBoarding.getTotalRecommendedretailprice() != null){
                    orderViphallDetailsVo.setTotalReCommenedRetatlPrice(orderBoarding.getTotalRecommendedretailprice().toString());
                }
                if (orderBoarding.getTotalSaleprice() != null){
                    orderViphallDetailsVo.setTotalsalePrice(orderBoarding.getTotalSaleprice().toString());
                }
                orderViphallDetailsVo.setPaymentStatus(orderBoarding.getPaymentStatus());
                if (orderBoarding.getPaymentAmount() != null){
                    orderViphallDetailsVo.setPaymentAmount(orderBoarding.getPaymentAmount().toString());
                }
                if (orderBoarding.getVoucherAmount() != null){
                    orderViphallDetailsVo.setVoucherAmount(orderBoarding.getVoucherAmount().toString());
                }
                if (orderBoarding.getPoints() != null){
                    orderViphallDetailsVo.setPoints(orderBoarding.getPoints().toString());
                }
                orderViphallDetailsVo.setPaymentType(orderBoarding.getMemberaccountPaymentmethod());

                List<OrderOperationlogVo> operationRecord = new ArrayList<>();
                if (orderBoarding.getOrderNumber() != null){
                    List<OrderOperationlog> orderOperationlogs = orderOperationlogMapper.orderOperationlogList(orderBoarding.getOrderNumber());
                    if (orderOperationlogs != null && orderOperationlogs.size() > 0){
                        for (OrderOperationlog orderOperationlog : orderOperationlogs) {
                            OrderOperationlogVo orderOperationlogVo = new OrderOperationlogVo();
                            orderOperationlogVo.setOperationId(orderOperationlog.getOperationId());
                            orderOperationlogVo.setOperationName(orderOperationlog.getOperationName());
                            orderOperationlogVo.setOperatorName(orderOperationlog.getOperatorName());
                            if (orderOperationlog.getCreateTime() != null){
                                orderOperationlogVo.setCreateTime(format.format(orderOperationlog.getCreateTime()));
                            }
                            orderOperationlogVo.setMemo(orderOperationlog.getMemo());
                            operationRecord.add(orderOperationlogVo);
                        }
                    }
                }

                orderViphallDetailsVo.setOperationRecord(operationRecord);

                VipchannelOrederTotalVo vipchannelOrederTotalVo = new VipchannelOrederTotalVo();
                Date date = new Date();
                vipchannelOrederTotalVo.setDate(format.format(date));

                orderViphallDetailsVo.setVipchannelOrederTotalVo(vipchannelOrederTotalVo);
                return orderViphallDetailsVo;
            }
            else {
                throw new Exception("未查到该笔订单");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 行程值机订单
     * */
    @Override
    public JourneyOrderBoardingVo selectOrderBoardingDetailed(Long orderboardingId) {
        OrderBoarding orderBoarding = orderBoardingMapper.selectOrderBoardingDetailed(orderboardingId);
        JourneyOrderBoardingVo journeyOrderBoardingVo = new JourneyOrderBoardingVo();
        journeyOrderBoardingVo.setOrderId(orderBoarding.getOrderboardingId().toString());
        journeyOrderBoardingVo.setBusinessType(EmHelper.businessType.CheckIn.getValue());
        journeyOrderBoardingVo.setActualPriceTotal("0");
        if (orderBoarding.getStatus().equals(EmHelper.SeatingArea.completed.getValue())){
            journeyOrderBoardingVo.setOrderStatusID("已完成");
        }
        else if (orderBoarding.getStatus().equals(EmHelper.SeatingArea.undone.getValue())){
            journeyOrderBoardingVo.setOrderStatusID("未完成");
        }
        else {
            journeyOrderBoardingVo.setOrderStatusID(orderBoarding.getStatus());
        }
        journeyOrderBoardingVo.setFlightNumber(orderBoarding.getFlightNumber());
        journeyOrderBoardingVo.setDepartureCity(orderBoarding.getDepartureCity());
        journeyOrderBoardingVo.setArrivalCity(orderBoarding.getArrivalCity());
        return journeyOrderBoardingVo;
    }

    /**
     * 值机退单
     * */
    @Override
    public int chargebackOrderBoarding(Long orderboardingId) {
        int i = orderBoardingMapper.chargebackOrderBoarding(orderboardingId);
        return i;
    }

    @Override
    public int queryVipBoardingOrderNumber(Long customerId) {
        return orderBoardingMapper.queryVipBoardingOrderNumber(customerId);
    }

    /**
     * 订单号获取值机订单信息
     * */
    @Override
    public OrderBoarding orderBoarding(String orderNum) {
        OrderBoarding orderBoarding = orderBoardingMapper.orderBoardingDetailed(orderNum);
        return orderBoarding;
    }

    /**
     * 获取年份
     * */
    public List<String> GetYears(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.YEAR, 0);
        Date date = calendar.getTime();
        calendar.add(Calendar.YEAR, -1);
        Date dateOne = calendar.getTime();
        calendar.add(Calendar.YEAR, -1);
        Date dateTwo = calendar.getTime();
        calendar.add(Calendar.YEAR, -1);
        Date dateThree = calendar.getTime();

        String formatDate = format.format(date);
        String formatOne = format.format(dateOne);
        String formatTwo = format.format(dateTwo);
        String formatThree = format.format(dateThree);
        List<String> dateList = new ArrayList<>();
        dateList.add(formatDate);
        dateList.add(formatOne);
        dateList.add(formatTwo);
        dateList.add(formatThree);

        return dateList;
    }
}
